﻿using SqlSugar;
using SqlSugar.Extensions;
using System.Linq.Expressions;
using Zhao.Common.Helper;
using Zhao.IServer;
using Zhao.Models.AppletDto;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Repository.Base;
using Zhao.Repository.UnitOfWork;

namespace Zhao.Service
{
    /// <summary>
    /// 订单表（支付凭证）
    ///</summary>
    public class OrdersServer : BaseService<Orders>, IOrdersServer
    {
        private readonly IUnitOfWork _unitOfWork;
        public OrdersServer(IBaseRepository<Orders> baseDal, IUnitOfWork unitOfWork) : base(baseDal, unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        public async Task<PageModel<OrderDTO>> QueryOrderPage(Expression<Func<Orders,Users,bool>> expression,int pageIndex,int pageSize)
        {
            //获取总条数
            RefAsync<int> totalCount = 0;

            var list=await _Client.Queryable<Orders>()
                .LeftJoin<Users>((a,b)=>a.UserId==b.UserID)
                .WhereIF(expression!=null,expression)
                .Select((a,b)=>new OrderDTO
                {
                    OrderID = a.OrderID,
                    UserName=b.Username,
                    TotalAmount=a.TotalAmount,
                    PaymentMethod=a.PaymentMethod,
                    PaymentTime=a.PaymentTime,
                    TransactionID=a.TransactionID,
                    CreatedAt=a.CreatedAt,
                    TypeId=a.TypeId,
                    Status=a.Status
                }).ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);

            int totalPage = (Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt();

            return new PageModel<OrderDTO>() { count = totalCount, PageCount = totalPage, PageIndex = pageIndex, PageSize = pageSize, data = list, code = totalCount == 0 ? -1 : 0, msg = totalCount == 0 ? "未查询到任何数据" : "" };
        }




        #region 小程序端API
        /// <summary>
        /// 获取用户账单详情
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public async Task<PageModel<OrderByUserIdInfoDto>> GetUserOrderAsync(int pageIndex, int pageSize, Expression<Func<Orders, bool>> expression)
        {
            //获取总条数
            RefAsync<int> totalCount = 0;

            var list = await _Client.Queryable<Orders>()
                             .WhereIF(expression!=null,expression)
                             .OrderBy(x=>x.CreatedAt, OrderByType.Desc)
                             .Select(a=>new OrderByUserIdInfoDto
                             {
                                 Id=a.OrderID,
                                 Detailed=a.RefundTransaction,
                                 Amount=a.TotalAmount,
                                 DateTime=a.CreatedAt,
                                 TypeId=a.TypeId,
                                 Status=a.Status,
                                 RefundAmount=a.RefundAmount
                             }).ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);

            int totalPage = (Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt();

            return new PageModel<OrderByUserIdInfoDto>() { count = totalCount, PageCount = totalPage, PageIndex = pageIndex, PageSize = pageSize, data = list, code = totalCount == 0 ? -1 : 0, msg = totalCount == 0 ? "未查询到任何数据" : "" };
        }


        /// <summary>
        ///  场馆预约订单的账单详情信息
        /// 获取订单详情（包含退款信息）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="orderId">订单ID</param>
        /// <returns>订单详情</returns>
        public async Task<ApiResult<OrderDetailDto>> GetOrderDetail(int userId, int orderId)
        {
            var result = new ApiResult<OrderDetailDto> { Success = false, Message = "获取订单详情失败" };

            try
            {
                // 1. 查询订单基本信息
                var order = await _Client.Queryable<Orders>()
                    .Where(o => o.OrderID == orderId && o.UserId == userId)
                    .FirstAsync();

                if (order == null)
                {
                    result.Message = "未找到指定的订单或您没有权限查看该订单";
                    return result;
                }

                // 2. 查询预约信息 - 不在SQL中调用方法
                var appointments = await _Client.Queryable<Appointments>()
                    .LeftJoin<Fields>((a, f) => a.FieldID == f.FieldID)
                    .LeftJoin<FieldTypes>((a, f, t) => f.FieldTypeID == t.FieldTypeID)
                    .Where((a, f, t) => a.OrderId == orderId)
                    .Select((a, f, t) => new
                    {
                        AppointmentId = a.AppointmentID,
                        FieldId = a.FieldID,
                        FieldName = f.FieldName,
                        FieldType = t.FieldTypeName,
                        DisplayDate = a.DisplayDate,
                        StartTime = a.StartTime,
                        EndTime = a.EndTime,
                        Status = a.Status,
                        Price = a.Price,
                        Name = a.Name,
                        Mobile = a.Mobile,
                        CreatedAt = a.CreatedAt,
                        UpdatedAt = a.UpdatedAt
                    })
                    .ToListAsync();

                // 转换为AppointmentDetailInfo并添加状态名称
                var appointmentDetails = appointments.Select(a => new AppointmentDetailInfo
                {
                    AppointmentId = a.AppointmentId,
                    FieldId = a.FieldId,
                    FieldName = a.FieldName,
                    FieldType = a.FieldType,
                    DisplayDate = a.DisplayDate,
                    StartTime = a.StartTime.ToString("HH:mm"),
                    EndTime = a.EndTime.ToString("HH:mm"),
                    Status = a.Status,
                    StatusName = GetAppointmentStatusName(a.Status),
                    Price = a.Price,
                    Name = a.Name,
                    Mobile = a.Mobile,
                    CreatedAt = a.CreatedAt,
                    UpdatedAt = a.UpdatedAt
                }).ToList();

                if (!appointmentDetails.Any())
                {
                    result.Message = "未找到该订单的预约记录";
                    return result;
                }

                // 3. 查询球馆信息
                // 直接从第一个预约中获取场馆ID
                var firstAppointment = appointmentDetails.First();
                var venueId = await _Client.Queryable<Appointments>()
                    .Where(a => a.AppointmentID == firstAppointment.AppointmentId)
                    .Select(a => a.VenueID)
                    .FirstAsync();

                var venue = await _Client.Queryable<Venues>()
                    .Where(v => v.VenueID == venueId)
                    .Select(v => new
                    {
                        v.VenueID,
                        v.VenueName,
                        v.Address,
                        v.Phone,
                        v.Images
                    })
                    .FirstAsync();

                // 4. 查询用户信息
                var user = await _Client.Queryable<Users>()
                    .Where(u => u.UserID == userId)
                    .Select(u => new
                    {
                        u.RealName,
                        u.Phone
                    })
                    .FirstAsync();

                // 5. 查询退款信息（如果有）
                RefundInfo refundInfo = null;
                if (order.Status == 5) // 已退款状态
                {
                    // 如果有退款订单ID，直接查询
                    Orders refundOrder = null;
                    if (order.RefundTransactionId.HasValue && order.RefundTransactionId.Value > 0)
                    {
                        refundOrder = await _Client.Queryable<Orders>()
                            .Where(o => o.OrderID == order.RefundTransactionId.Value)
                            .FirstAsync();
                    }
                    else
                    {
                        // 兼容旧数据，查找与该订单相关的退款记录
                        refundOrder = await _Client.Queryable<Orders>()
                            .Where(o => o.TypeId == 9 && o.UserId == userId &&
                                    o.CreatedAt > order.CreatedAt &&
                                    o.TotalAmount == order.TotalAmount)
                            .OrderByDescending(o => o.CreatedAt)
                            .FirstAsync();
                    }

                    if (refundOrder != null)
                    {
                        refundInfo = new RefundInfo
                        {
                            RefundOrderId = refundOrder.OrderID,
                            RefundAmount = order.RefundAmount ?? refundOrder.TotalAmount,
                            RefundTime = refundOrder.CreatedAt,
                            RefundTransactionId = order.RefundTransaction,
                            Status = refundOrder.Status,
                            StatusName = GetRefundOrderStatusName(refundOrder.Status)
                        };
                    }
                    else if (order.RefundAmount.HasValue) // 如果没有找到退款订单但有退款金额
                    {
                        // 使用原订单中的退款信息
                        refundInfo = new RefundInfo
                        {
                            RefundOrderId = order.RefundTransactionId ?? 0,
                            RefundAmount = order.RefundAmount.Value,
                            RefundTime = order.PaymentTime, // 使用支付时间作为退款时间
                            RefundTransactionId = order.RefundTransaction,
                            Status = order.Status, // 已完成
                            StatusName = "部分退款"
                        };
                    }
                }


                // 7. 组装订单详情
                var orderDetail = new OrderDetailDto
                {
                    OrderId = order.OrderID,
                    TotalAmount = order.TotalAmount,
                    PaymentMethod = order.PaymentMethod,
                    PaymentMethodName = GetPaymentMethodName(order.PaymentMethod),
                    PaymentTime = order.PaymentTime,
                    CreatedAt = order.CreatedAt,
                    OrderStatus = order.Status,
                    OrderStatusName = GetOrderStatusName(order.Status),
                    TypeId = order.TypeId,
                    TypeName = GetOrderTypeName(order.TypeId),
                    TransactionID = order.TransactionID,
                    UserName = user?.RealName,
                    Phone = user?.Phone,
                    VenueId = venue?.VenueID ?? Guid.Empty,
                    VenueName = venue?.VenueName,
                    VenueAddress = venue?.Address,
                    VenuePhone = venue?.Phone,
                    VenueImage = venue?.Images,
                    DisplayDate = firstAppointment.DisplayDate,
                    Appointments = appointmentDetails,
                    RefundInfo = refundInfo
                };

                result.Success = true;
                result.Message = "获取订单详情成功";
                result.Data = orderDetail;
                return result;
            }
            catch (Exception ex)
            {
                result.Message = $"处理请求时发生错误: {ex.Message}";
                return result;
            }
        }

        /// <summary>
        /// 获取活动订单详情
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="orderId">订单ID</param>
        /// <returns>活动订单详情</returns>
        public async Task<ApiResult<ActivityOrderDetailDto>> GetActivityOrderDetail(int userId, int orderId)
        {
            var result = new ApiResult<ActivityOrderDetailDto> { Success = false, Message = "获取活动订单详情失败" };

            try
            {
                // 1. 查询订单基本信息
                var order = await _Client.Queryable<Orders>()
                    .Where(o => o.OrderID == orderId && o.UserId == userId)
                    .FirstAsync();

                if (order == null)
                {
                    result.Message = "未找到指定的订单或您没有权限查看该订单";
                    return result;
                }

                // 验证是否为活动订单
                if (order.TypeId != 5 && order.TypeId != 11) // 5-活动支付 11-订单补购
                {
                    result.Message = "该订单不是活动订单";
                    return result;
                }

                // 2. 查询用户信息
                var user = await _Client.Queryable<Users>()
                    .Where(u => u.UserID == userId)
                    .Select(u => new
                    {
                        u.RealName,
                        u.Phone
                    })
                    .FirstAsync();

                // 3. 查询活动信息
                if (!order.ActivityId.HasValue)
                {
                    result.Message = "订单未关联活动信息";
                    return result;
                }

                var activity = await _Client.Queryable<Activities>()
                    .LeftJoin<Venues>((a, v) => a.VenueID == v.VenueID)
                    .Where((a, v) => a.ActivityID == order.ActivityId.Value)
                    .Select((a, v) => new
                    {
                        ActivityID = a.ActivityID,
                        Title = a.Title,
                        Description = a.Description,
                        StartTime = a.StartTime,
                        EndTime = a.EndTime,
                        Price = a.Price,
                        PriceType = a.PriceType,
                        Status = a.Status,
                        DisplayDate = a.DisplayDate,
                        Image = a.Image,
                        VenueID = v.VenueID,
                        VenueName = v.VenueName,
                        VenueAddress = v.Address,
                        VenuePhone = v.Phone,
                        VenueImage = v.Images
                    })
                    .FirstAsync();

                if (activity == null)
                {
                    result.Message = "未找到相关活动信息";
                    return result;
                }

                // 4. 查询活动成员信息（获取男女人数）
                var member = await _Client.Queryable<ActivityMembers>()
                    .Where(m => m.ActivityId == activity.ActivityID && m.UserId == userId && m.OrderId == orderId)
                    .FirstAsync();

                if (member == null)
                {
                    result.Message = "未找到活动报名信息";
                    return result;
                }

                // 5. 查询退款信息（如果有）
                RefundInfo refundInfo = null;
                if (order.Status == 5) // 已退款状态
                {
                    // 如果有退款订单ID，直接查询
                    Orders refundOrder = null;
                    if (order.RefundTransactionId.HasValue && order.RefundTransactionId.Value > 0)
                    {
                        refundOrder = await _Client.Queryable<Orders>()
                            .Where(o => o.OrderID == order.RefundTransactionId.Value)
                            .FirstAsync();
                    }
                    else
                    {
                        // 兼容旧数据，查找与该订单相关的退款记录
                        refundOrder = await _Client.Queryable<Orders>()
                            .Where(o => o.TypeId == 9 && o.UserId == userId &&
                                    o.CreatedAt > order.CreatedAt &&
                                    o.TotalAmount == order.TotalAmount)
                            .OrderByDescending(o => o.CreatedAt)
                            .FirstAsync();
                    }

                    if (refundOrder != null)
                    {
                        refundInfo = new RefundInfo
                        {
                            RefundOrderId = refundOrder.OrderID,
                            RefundAmount = order.RefundAmount ?? refundOrder.TotalAmount,
                            RefundTime = refundOrder.CreatedAt,
                            RefundTransactionId = order.RefundTransaction,
                            Status = refundOrder.Status,
                            StatusName = GetRefundOrderStatusName(refundOrder.Status)
                        };
                    }
                    else if (order.RefundAmount.HasValue) // 如果没有找到退款订单但有退款金额
                    {
                        // 使用原订单中的退款信息
                        refundInfo = new RefundInfo
                        {
                            RefundOrderId = order.RefundTransactionId ?? 0,
                            RefundAmount = order.RefundAmount.Value,
                            RefundTime = order.PaymentTime, // 使用支付时间作为退款时间
                            RefundTransactionId = order.RefundTransaction,
                            Status = order.Status, // 已完成
                            StatusName = "部分退款"
                        };
                    }
                }

                // 6. 组装活动订单详情
                var activityOrderDetail = new ActivityOrderDetailDto
                {
                    OrderId = order.OrderID,
                    TotalAmount = order.TotalAmount,
                    PaymentMethod = order.PaymentMethod,
                    PaymentMethodName = GetPaymentMethodName(order.PaymentMethod),
                    PaymentTime = order.PaymentTime,
                    CreatedAt = order.CreatedAt,
                    OrderStatus = order.Status,
                    OrderStatusName = GetOrderStatusName(order.Status),
                    TypeId = order.TypeId,
                    TypeName = GetOrderTypeName(order.TypeId),
                    TransactionID = order.TransactionID,
                    UserName = user?.RealName,
                    Phone = user?.Phone,

                    // 活动信息
                    ActivityId = activity.ActivityID,
                    ActivityTitle = activity.Title,
                    ActivityDescription = activity.Description,
                    ActivityStartTime = activity.StartTime,
                    ActivityEndTime = activity.EndTime,
                    ActivityPrice = activity.Price,
                    ActivityPriceType = activity.PriceType,
                    ActivityStatus = activity.Status,
                    ActivityStatusName = GetActivityStatusName(activity.Status),
                    ActivityImage = activity.Image,
                    DisplayDate = activity.DisplayDate,

                    // 场馆信息
                    VenueId = activity.VenueID,
                    VenueName = activity.VenueName,
                    VenueAddress = activity.VenueAddress,
                    VenuePhone = activity.VenuePhone,
                    VenueImage = activity.VenueImage,

                    // 报名人数
                    MaleNumber = member.MaleNumber,
                    FemaleNumber = member.FemaleNumber,

                    // 退款信息
                    RefundInfo = refundInfo
                };

                result.Success = true;
                result.Message = "获取活动订单详情成功";
                result.Data = activityOrderDetail;
                return result;
            }
            catch (Exception ex)
            {
                result.Message = $"处理请求时发生错误: {ex.Message}";
                return result;
            }
        }

        /// <summary>
        /// 获取预约状态名称
        /// </summary>
        private string GetAppointmentStatusName(short status)
        {
            return status switch
            {
                0 => "待支付",
                3 => "已预约",
                5 => "已完成",
                7 => "已取消",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取订单状态名称
        /// </summary>
        private string GetOrderStatusName(short status)
        {
            return status switch
            {
                1 => "待支付",
                3 => "已支付",
                5 => "已退款",
                _ => "未知状态"

            };
        }

        /// <summary>
        /// 获取退款订单的状态名称
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string GetRefundOrderStatusName(short status)
        {
            return status switch
            {
                1 => "待退回",
                3 => "退款成功",
                5 => "取消退款",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取支付方式名称
        /// </summary>
        private string GetPaymentMethodName(short? paymentMethod)
        {
            return paymentMethod switch
            {
                1 => "余额支付",
                2 => "支付宝支付",
                3 => "微信支付",
                _ => "未知方式"
            };
        }

        /// <summary>
        /// 获取订单类型名称
        /// </summary>
        private string GetOrderTypeName(short typeId)
        {
            return typeId switch
            {
                1 => "充值",
                3 => "提现",
                5 => "活动支付",
                7 => "场地预定",
                9 => "订单取消退款",
                10 => "部分退款",
                11 => "订单补购",
                _ => "未知类型"
            };
        }

        /// <summary>
        /// 获取活动状态名称
        /// </summary>
        private string GetActivityStatusName(short status)
        {
            return status switch
            {
                0 => "未开始",
                1 => "报名中",
                3 => "进行中",
                5 => "已结束",
                7 => "已取消",
                9 => "待结算",
                _ => "未知状态"
            };
        }

        #endregion
    }
}
